package smartgrid;

import java.util.Arrays;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.Stateless;
import org.hibernate.criterion.Restrictions;
import org.orm.PersistentException;

@Stateless
public class SuppliersManager implements SuppliersInfo {

    /**
     * 
     * @return A "Supplier" list
     */
    @Override
    public List<Supplier> getSuppliers() {
        smartgrid.Supplier[] suppliers = smartgrid.Supplier.listSupplierByQuery(null, null);
        if(suppliers != null)
            return Arrays.asList(suppliers);
        else
            return null;
    }

    /**
     * 
     * @return A "Supplier" list by country
     */
    @Override
    public List<Supplier> getSuppliersCountry(String country) {
        smartgrid.Supplier[] suppliers = null;

        try {

            SupplierCriteria crit = new SupplierCriteria();
            crit.add(Restrictions.eq("country", country));
            suppliers = smartgrid.Supplier.listSupplierByCriteria(crit);

        } catch (PersistentException ex) {
            Logger.getLogger(SuppliersManager.class.getName()).log(Level.SEVERE, null, ex);
        }

        return Arrays.asList(suppliers);
    }

    /**
     * Inserts one Supplier
     * 
     * @param name Supplier's name
     * @param country Supplier's Contry
     * @return If success: true
     */
    @Override
    public Boolean insertSupplier(String name, String country) {
        try {
            smartgrid.SupplierCriteria crit = new SupplierCriteria();
            crit.add(Restrictions.eq("Name", name));
            crit.add(Restrictions.eq("Country", country));

            smartgrid.Supplier supplier = smartgrid.Supplier.loadSupplierByCriteria(crit);
            if (supplier == null) {
                smartgrid.SupplierProcessor supProcess = new smartgrid.SupplierProcessor();
                supProcess.setName(name);
                supProcess.setCountry(country);
                supProcess.setAction("insert");

                if (supProcess.process().equals("Insert success")) {
                    return true;
                }
            }
        } catch (PersistentException ex) {
            Logger.getLogger(FacebookAccountManager.class.getName()).log(Level.SEVERE, null, ex);
        }

        return false;
    }
}